<template>
  <Drawer>
    <!-- 表单 -->
    <FosoForm
      ref="userFormRef"
      :form-columns="formColumns"
      :form-columns-num="24"
      :form-data="formData"
      :form-rules="formRules"
      label-position="top"
      label-width="100px"
    >
      <template #avater>
        <!-- 头像 -->
        <AvatarUpload />
      </template>
    </FosoForm>
  </Drawer>
</template>

<script lang="ts" setup>
import type { DepartmentInfo } from '#/api/sys/model/departmentModel';
import type { PositionInfo } from '#/api/sys/model/positionModel';
import type { UserInfo } from '#/api/sys/model/userModel';

import { useVbenDrawer } from '@vben/common-ui';
import { $t } from '@vben/locales';

import { getDepartmentList } from '#/api/sys/department';
import { getPositionList } from '#/api/sys/position';
import { getRoleList } from '#/api/sys/role';
import { createUser, getUserById, updateUser } from '#/api/sys/user';

import AvatarUpload from './AvatarUpload.vue';
// 定义 emit 类型
interface Emit {
  (e: 'refresh', data?: any): void;
}
// 创建 emit 函数
const emit = defineEmits<Emit>();

// 表单实例
const userFormRef = ref();

// 表单数据
const formData = ref<UserInfo>({
  status: 1, // 默认启动状态
});

const positionOptions = ref<any[]>([]); // 职位列表
const departmentOptions = ref<any[]>([]); // 部门列表
const roleOptions = ref<any[]>([]); // 角色列表

// 校验规则
const formRules = ref({
  username: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  nickname: [{ required: true, message: '请输入年龄', trigger: 'blur' }],
  // 邮箱
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱', trigger: 'blur' },
  ],
  // 角色
  roleIds: [
    { required: true, message: '请选择角色', trigger: 'change' },
    { type: 'array', message: '请选择角色', trigger: 'change' },
  ],
  // 部门
  departmentId: [
    { required: true, message: '请选择部门', trigger: 'change' },
    { type: 'number', message: '请选择部门', trigger: 'change' },
  ],
  // 职位
  positionId: [{ required: true, message: '请选择职位', trigger: 'change' }],
});

// 弹窗连接
const [Drawer, drawerApi] = useVbenDrawer({
  loading: true, // 不显示加载中状态
  async onConfirm() {
    const { type, id } = drawerApi.getData<Record<string, any>>();
    await userFormRef.value?.formRef?.validate();

    if (type === 'addData') {
      addOrEditDictionaryHandle(formData.value);
    }
    if (type === 'editData') {
      addOrEditDictionaryHandle(formData.value, id);
    }
  },
  // 弹窗打开时触发
  async onOpenChange(isOpen: boolean) {
    if (isOpen) {
      getDepListData();
      // 设置默认值
      const { type, id } = drawerApi.getData<Record<string, any>>();
      // 新增
      if (type === 'addData') {
        drawerApi.setState({ loading: false });
      }
      // 编辑打开弹窗时回显数据
      if (type === 'editData') {
        getUserDetailInfo(id);
      }
    } else {
      // 关闭弹窗时重置表单
      userFormRef.value?.formRef?.resetFields();
    }
  },
});

// 表单配置项
const formColumns = computed(() => [
  {
    label: $t('sys.user.avatar'), // 表单项的标签,
    prop: 'avater',
    xType: 'upload',
  },
  {
    label: $t('sys.login.username'),
    prop: 'username',
    xType: 'Input',
    hidden: false,
    componentProps: {
      placeholder: $t('common.form.pleaseInput'),
      clearable: true,
    },
  },
  {
    label: $t('sys.user.nickname'),
    prop: 'nickname',
    xType: 'Input',
    componentProps: {
      placeholder: $t('common.form.pleaseInput'),
      clearable: true,
    },
  },
  {
    label: $t('sys.user.description'),
    prop: 'description',
    xType: 'Input',
    componentProps: {
      placeholder: $t('common.form.pleaseInput'),
      clearable: true, // el-select 的属性
    },
  },
  {
    label: $t('sys.user.homePath'),
    prop: 'homePath',
    xType: 'Input',
    componentProps: {
      placeholder: $t('common.form.pleaseInput'),

      clearable: true, // el-select 的属性
    },
  },
  {
    label: $t('sys.login.mobile'),
    prop: 'mobile',
    xType: 'Input', // 自行配置行宽
    componentProps: {
      placeholder: $t('common.form.pleaseInput'),
      clearable: true,
    },
  },
  {
    label: $t('sys.login.email'),
    prop: 'email',
    xType: 'Input', // 自行配置行宽
    componentProps: {
      placeholder: $t('common.form.pleaseInput'),
      clearable: true,
    },
  },
  {
    label: $t('sys.login.password'),
    prop: 'password',
    xType: 'Input', // 自行配置行宽
    componentProps: {
      type: 'password',
      placeholder: $t('common.form.pleaseInput'),
      clearable: true,
    },
  },
  {
    label: $t('sys.role.roleTitle'),
    prop: 'roleIds',
    xType: 'Select', // 自行配置行宽
    componentProps: {
      multiple: true,
      placeholder: $t('common.form.pleaseInput'),
      clearable: true,
      options: roleOptions.value,
    },
  },
  {
    label: $t('sys.department.userDepartment'),
    prop: 'departmentId',
    xType: 'Select', // 自行配置行宽
    componentProps: {
      placeholder: $t('common.form.pleaseInput'),
      clearable: true,
      options: departmentOptions.value,
    },
  },
  {
    label: $t('sys.position.userPosition'),
    prop: 'positionId',
    xType: 'Select', // 自行配置行宽
    componentProps: {
      multiple: true,
      placeholder: $t('common.form.pleaseInput'),
      clearable: true,
      options: positionOptions.value,
    },
  },
  {
    label: $t('sys.role.status'),
    prop: 'status',
    xType: 'RadioGroup',
    componentProps: {
      options: [
        { label: $t('sys.role.start'), value: 1 },
        { label: $t('sys.role.stop'), value: 0 },
      ],
    },
  },
]);

/**
 * @author Buke
 * @description 新增或者编辑
 * @param {Record<string, any>} formData - 表单数据对象。
 * @param {number} id - ID（可选）。
 * @returns {void}
 * @todo 用户新增报错，待解决,新增状态没有改变，待解决
 */
async function addOrEditDictionaryHandle(
  formData: Record<string, any>,
  id?: number,
): Promise<void> {
  try {
    const data = {
      ...formData,
      id,
    };
    id ? await updateUser(data) : await createUser(data);
    ElMessage.success('操作成功');
    emit('refresh');
  } catch {
    ElMessage.error('新增失败');
  }
}

/**
 * @author Buke
 * @description 详情数据回显
 * @param {number} id - 要回显的职位ID。
 * @returns {void}
 * @todo 待解决，用户详情数据回显问题，待解决
 */
async function getUserDetailInfo(id: any): Promise<void> {
  try {
    drawerApi.setState({ loading: true });

    const res = await getUserById(id);
    formData.value = res;
    // 关闭加载中状态
    drawerApi.setState({ loading: false });
  } catch {
    ElMessage.error('获取详情失败');
    // 关闭加载中状态
    drawerApi.setState({ loading: false });
  }
}
/**
 * @author Buke
 * @description 获取部门与职位与角色数据
 * @returns {void}
 */
async function getDepListData(): Promise<void> {
  try {
    // 并行请求
    const [positionRes, departmentRes, roleRes] = await Promise.all([
      getPositionList({ page: 1, pageSize: 500, status: 1 }),
      getDepartmentList({ page: 1, pageSize: 500, status: 1 }),
      getRoleList({ page: 1, pageSize: 500, status: 1 }),
    ]);
    // 处理部门选项
    departmentOptions.value = departmentRes.data.map(
      (item: DepartmentInfo) => ({
        label: item.name || '',
        value: item.id,
      }),
    );
    // 处理职位选项（使用国际化）
    positionOptions.value = positionRes.data.map((item: PositionInfo) => ({
      label: item.name || '',
      value: item.id,
    }));
    // 处理角色选项（使用国际化）
    roleOptions.value = roleRes.data.map((item: PositionInfo) => ({
      label: item.name || '',
      value: item.id,
    }));
  } catch {
    ElMessage.error('获取部门或职位数据失败');
  }
}
</script>
